/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 * OrderSweepScurrySave
 * 赶房 {"whsk_Order_Sweep":{"room":"0411","wuserid":"S03","iuserid":"S03","remark":"123456"}}
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    Modal, Platform, BackHandler, ToastAndroid, TextInput,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './guestServiceScreen.Style'
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent";
import AntDesign from "react-native-vector-icons/AntDesign";
import FontAwesome from "react-native-vector-icons/FontAwesome"
import DatePicker from 'react-native-datepicker'
import {
    COLOR_FOCUS,
    COLOR_HEADER_END,
    COLOR_HEADER_START,
    COLOR_THEME,
    FONT_COLOR_SUB_TITLE, FONT_COLOR_TITLE,
    FONT_SIZE_TITLE
} from "../../../constant/PHColors";
import BottomButtonView from "../../../component/BottomButtonView/BottomButtonView";
import Entypo from "react-native-vector-icons/Entypo";
import LinearGradient from "react-native-linear-gradient";
import {SaveRepairWorkOrder} from "../../job/WorkOrder/CreateRepairWorkOrderScreen/Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import {getScurryDefault,saveScurryOrder,saveGuestService} from "./Actions"
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import SelectFromBottomPlugIn from "../../custom/selectFromBottom/selectFromBottomPlugIn";

class guestServiceScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `催服务`,
    });

    // 构造
    constructor(props) {
        super(props);

        let outjson = {};
        if(this.props.navigation.getParam("room") && this.props.navigation.getParam("room")!==""){
            this.props.navigation.getParam("room").split(',').map((item,index)=>{
                outjson[item] = {"room":item,"wuserid":""}
            });
        }

        let date = new Date();
        let year = date.getFullYear().toString();
        let month = (date.getMonth()+1).toString();
        if(Number(month)<10){
            month = '0'+month
        }
        let day = date.getDate().toString();
        if(Number(day)<10){
            day = '0'+day
        }
        let nowDate = year+'-'+month+'-'+day;

        // 初始状态
        this.state = {
            checkModalVisible:false,
            outJson:outjson,         //{"0405":{"room":"0405","wuserid":"","iuserid":"","remark":""},0406:{"whsk_Order_Sweep":{"room":"0406","wuserid":"","iuserid":"","remark":""}}}
            room:this.props.navigation.getParam("room")?this.props.navigation.getParam("room"):'',
            room_info:outjson,
            remark:'',
            returnModalVisible:false,           //是否放弃新建模态
            alertModalVisible:false,
            ifLocalPage:true,
            alertStr:{},
            alertData:{},
            date:nowDate,
            phone:'',
            ifcopy:true,
        };

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;


        if (nextProps.onGetScurryDefault !== this.props.onGetScurryDefault && nextProps.onGetScurryDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onGetScurryDefault.RETURN === ReturnStatus.Success) {
                console.log(JSON.stringify(this.state.room_info))
                let outjson = {};
                nextProps.onGetScurryDefault.data.map((item,index)=>{
                    outjson[item.room] = {"room":item.room,"wuserid":item.wuserid}
                });
                this.setState({
                    room:this.state.room,
                    outJson:outjson,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onGetScurryDefault.MSG))
            }
        }

        if (nextProps.onSaveGuestService !== this.props.onSaveGuestService && nextProps.onSaveGuestService.fetchStatus === FetchStatus.Success) {
            if (nextProps.onSaveGuestService.RETURN === ReturnStatus.Success) {
                this.setState({
                    checkModalVisible:false,
                    returnModalVisible:false,
                    alertModalVisible:false,
                });

                this.saveTimes = this.saveTimes-1;
                if(this.saveTimes<=0){
                    this.props.navigation.state.params.callBack();
                }

            }else if(nextProps.onSaveGuestService.RETURN === '-10'){
                this.setState({
                    alertModalVisible:true,
                    alertData:nextProps.onSaveGuestService,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onSaveGuestService.MSG))
            }
        }

    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"work_Order_sweep":{"place":this.state.room,"position": "对客服务"}};
        dispatch(getScurryDefault(JSON.stringify(str)))
    }
    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.state.checkModalVisible===false&&this.props.navigation.isFocused()===true){
            this.setState({
                checkModalVisible:false,
                returnModalVisible:true,
                alertModalVisible:false,
            });
            return true;
        }else{
            return false;
        }
    };

    render() {
        let {dispatch} = this.props;
        let _this = this;
        return (
            <SafeAreaView style={styles.body}>
                <ScrollView style={styles.body}>

                    <DividingLineViewComponent lineHeight={10}/>

                    {/* 地点 */}
                    <View style={{backgroundColor: '#FFF'}}>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            this.props.navigation.navigate('RetrieveRoomsViewScreen',{multi:true,checkedRoom:this.state.room,callBack:(rooms_arr)=>{
                                    _this.props.navigation.navigate('guestServiceScreen');

                                    let rooms_info = {};
                                    let rooms = [];
                                    rooms_arr.map((item,index)=>{
                                        rooms.push(item.room);
                                        rooms_info[item.room] = item;
                                    })
                                    this.state.room_info = rooms_info;
                                    this.getOutJson(rooms.join(','));
                                }});
                        }}>
                            <View style={styles.itemHeader}>
                                <View style={styles.itemHeaderLeft}>
                                    <Text style={styles.itemHeaderText}>
                                        地点
                                    </Text>
                                </View>
                                <View style={styles.itemHeaderRight}>
                                    <AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                </View>
                            </View>
                        </TouchableOpacity>

                        <DividingLineViewComponent lineHeight={1}/>

                        <View style={{margin: 15,flexDirection:'row'}}>
                            <TextInput
                                placeholder={'选择地点'}
                                style={{
                                    fontSize: 16,
                                    padding: 0,
                                    color:(this.state.room===""||typeof (this.state.room)==='undefined')?'#f1f1f1':'#000000',
                                }}
                                numberOfLines={1}
                                underlineColorAndroid={'transparent'}
                                onChangeText={text=>{

                                }}
                                defaultValue = {this.state.room}
                                editable = {false}
                            />
                            {
                                (this.state.room!==""&&typeof (this.state.room)!=='undefined') && (
                                    <View style={styles.itemHeaderRight}>
                                        <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{
                                            this.getOutJson('');
                                        }}/>
                                    </View>
                                )
                            }
                        </View>
                    </View>

                    <DividingLineViewComponent lineHeight={10}/>

                    {/* 清洁人 */}
                    {
                        <View style={{backgroundColor: '#FFF'}}>
                            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                if(this.state.room.split(',').length>1){

                                }else{

                                }
                            }}>
                                <View style={styles.itemHeader}>
                                    <View style={styles.itemHeaderLeft}>
                                        <Text style={styles.itemHeaderText}>
                                            处理人
                                        </Text>
                                    </View>
                                    <View style={styles.itemHeaderRight}>
                                        {/*<AntDesign name={'right'} size={14} style={{color: FONT_COLOR_SUB_TITLE}}/>*/}
                                    </View>
                                </View>
                            </TouchableOpacity>

                            <DividingLineViewComponent lineHeight={1}/>

                            {
                                this.show_order()
                            }

                        </View>
                    }

                    <DividingLineViewComponent lineHeight={10}/>
                    {
                        <View style={{backgroundColor: '#FFF'}}>
                            <View style={styles.itemHeader}>
                                <View style={styles.itemHeaderLeft}>
                                    <Text style={styles.itemHeaderText}>
                                        工单特点
                                    </Text>
                                </View>
                                <View style={styles.itemHeaderRight}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        // this.setState({
                                        //     ifcopy:!this.state.ifcopy,
                                        // })
                                    }}>
                                        <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>

                                            {
                                                (this.state.ifcopy)?
                                                    (
                                                        <Image style={{width: 18, height: 18}} source={require("../../../resource/login/dl_yixuan.png")}/>
                                                    )
                                                    :
                                                    (
                                                        <Image style={{width: 18, height: 18}} source={require("../../../resource/login/dl_weixuan.png")}/>
                                                    )
                                            }
                                            <Text style={{fontSize: 16, marginLeft: 5}}>
                                                抄送主管
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>

                    }

                    <DividingLineViewComponent lineHeight={10}/>
                    {
                        <View style={{backgroundColor: '#FFF'}}>
                            <View style={styles.itemHeader}>
                                <View style={styles.itemHeaderLeft}>
                                    <Text style={styles.itemHeaderText}>
                                        备注
                                    </Text>
                                </View>
                                <View style={styles.itemHeaderRight}>
                                    <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                                        {this.state.remark.length}
                                        <Text style={{fontSize: 16, color: FONT_COLOR_SUB_TITLE}}>
                                            /100
                                        </Text>
                                    </Text>
                                </View>
                            </View>

                            <DividingLineViewComponent lineHeight={1}/>

                            <View style={{margin: 15, height: 120}}>
                                <TextInput
                                    placeholder={'写下客人的详细要求，以及打扫类型，是住房打扫或其他打扫'}
                                    multiline={true}
                                    maxLength={100}
                                    style={{
                                        fontSize: 16,
                                        padding: 0,
                                        height:120,
                                        textAlignVertical: "top",
                                        lineHeight:25,
                                    }}
                                    underlineColorAndroid={'transparent'}
                                    onChangeText={text => {
                                        if(text.length>100){
                                            text = text.substring(0,100)
                                        }
                                        this.setState({
                                            remark:text,
                                        })
                                    }}
                                />
                            </View>
                        </View>
                    }

                </ScrollView>

                <BottomButtonView title={'完成'} onSubmitClick={() => {
                    this._onCheck()
                }}/>

                <Modal visible={this.state.checkModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                    <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                        <View style={styles.checkModalBody}>
                            <View style={styles.checkModalHeader}>
                                <Text style={styles.checkModalHeaderText}>
                                    确认下单？
                                </Text>
                            </View>
                            <View style={styles.checkModalCenter}>
                                <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                    this.setState({
                                        checkModalVisible:false,
                                    })
                                }}>
                                    <Text style={{color:'black'}}>
                                        取消
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                    this._onSubmitClick()
                                }}>
                                    <Text style={{color:'white'}}>
                                        下单
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </Modal>

                <Modal visible={this.state.returnModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={()=> this.onRequestClose()}>
                        <View style={styles.modalContainer} onPress={()=> this.onRequestClose()}>
                            <View style={styles.checkModalBody}>
                                <View style={styles.checkModalHeader}>
                                    <Text style={styles.checkModalHeaderText}>
                                        放弃新建工单么？
                                    </Text>
                                </View>
                                <View style={styles.checkModalCenter}>
                                    <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                        this.setState({
                                            returnModalVisible:false,
                                        });
                                        this.props.navigation.goBack();
                                    }}>
                                        <Text style={{color:'black'}}>
                                            放弃
                                        </Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                        this.setState({
                                            returnModalVisible:false,
                                        })
                                    }}>
                                        <Text style={{color:'white'}}>
                                            继续新建
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

                {/*alert-10模态框*/}
                <Modal visible={this.state.alertModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                        this.onRequestClose();
                    }}>
                        <View style={styles.checkmodalContainer} >
                            <View style={styles.checkModalBody}>
                                <View style={styles.checkModalHeader}>
                                    <Text style={styles.checkModalHeaderText}>
                                        {this.state.alertData.MSG}
                                    </Text>
                                </View>
                                <View style={styles.checkModalCenter}>
                                    <TouchableOpacity  style={styles.checkModalCenterLeft} onPress={()=>{
                                        this.setState({
                                            alertModalVisible:false,
                                        })
                                    }}>
                                        <Text style={{color:'black',fontSize:20}}>
                                            取消
                                        </Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.checkModalCenterRight} onPress={()=>{
                                        this.setState({
                                            alertModalVisible:false,
                                        });
                                        let str = this.state.alertStr;
                                        // str.arg={};
                                        str.arg[this.state.alertData.checkbox]='yes';
                                        dispatch(saveGuestService(JSON.stringify(str)));
                                    }}>
                                        <Text style={{color:'white',fontSize:20}}>
                                            继续
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

            </SafeAreaView>
        )
    }

    show_order(){
        let _this = this;
        let html_arr  = [];

        for(let key in this.state.outJson){
            let json = this.state.outJson[key];
            let html = (
                <View style={{flex: 1,flexDirection:'row',height:40,}}>
                    <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                        <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                            {json.room}
                        </Text>
                    </View>
                    <View style={{width:(SCREEN_WIDTH-80),flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                        {
                            (json.wuserid==='')
                                ?
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                                                _this.props.navigation.navigate('guestServiceScreen');
                                                this.state.outJson[key].wuserid = users;
                                                this.setState({
                                                    outJson:this.state.outJson,
                                                })
                                            }})
                                    }}>
                                        <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_SUB_TITLE}}>
                                                请选择
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                                :
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:json.wuserid,callBack:(users)=>{
                                                _this.props.navigation.navigate('guestServiceScreen');
                                                this.state.outJson[key].wuserid = users;
                                                this.setState({
                                                    outJson:this.state.outJson,
                                                })
                                            }})
                                    }}>
                                        <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                            <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                                {json.wuserid}
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                        }
                    </View>
                </View>
            );
            let html1 = (
                <DividingLineViewComponent lineHeight={1}/>
            );
            html_arr.push(html1);
            html_arr.push(html);
        }
        if(html_arr.length>0){
            let title_html = (
                <View style={{flex: 1,flexDirection:'row',height:40}}>
                    <View style={{width:80,flexDirection:'row',justifyContent: 'center',alignItems: 'center',height:40}}>
                        <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                            房号
                        </Text>
                    </View>
                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                        this.props.navigation.navigate("RetrieveWHSKAlinusersScreen",{multi:false,checkedUser:'',callBack:(users)=>{
                                _this.props.navigation.navigate('guestServiceScreen');
                                let newOutJson = this.state.outJson;
                                for(let json in newOutJson){
                                    newOutJson[json].wuserid = users;
                                }
                                this.setState({
                                    outJson:newOutJson,
                                })
                            }})
                    }}>
                        <View style={{width:(SCREEN_WIDTH-80),flexDirection:'row',alignItems:'center',justifyContent:'center',height:40}}>
                            <View style={{flexDirection:'row',justifyContent: 'center',alignItems: 'center'}}>
                                <Text style={{fontSize: 16,color:FONT_COLOR_TITLE}}>
                                    清洁人
                                    <FontAwesome name={'question-circle'} size={18} style={{color: COLOR_FOCUS,marginLeft: 2,}}/>
                                </Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
            )
            html_arr.splice(0,0,title_html)
        }

        return html_arr;
    };

    //检查数据格式
    _onCheck=()=>{
        this.setState({
            checkModalVisible:true,
        })
    };

    getOutJson=(rooms)=>{
        let {dispatch} = this.props;

        let str = {"work_Order_sweep":{"place":rooms,"position": "对客服务"}}
        this.state.room = rooms;
        dispatch(getScurryDefault(JSON.stringify(str)))

    };

    //确认提交
    _onSubmitClick=()=>{


        this.saveTimes=0;
        for(let json in this.state.outJson){
            this.saveTimes=this.saveTimes+1;
        }

        for(let json in this.state.outJson){
            let {dispatch} = this.props;

            let info = this.state.outJson[json];

            let ifcopy = '0';
            if(this.state.ifcopy){
                ifcopy = '1';
            }

            let outJson = {"arg":{"postgledger":"no"},"whsk_Order_detail":[],"whsk_Order":{"place":info.room,"ordertype":"客人催服务","ifcopy":ifcopy,"remark":this.state.remark,"wuserid":info.wuserid}};

            this.state.alertStr = outJson;

            console.log(JSON.stringify(outJson));

            dispatch(saveGuestService(JSON.stringify(outJson),''));

        }



        // dispatch(orderSweepSave(JSON.stringify(outJson)));

    }

    onRequestClose(){
        this.setState({
            checkModalVisible:false,
            returnModalVisible:false,
            alertModalVisible:false,
        })
    }
}

const props = state => {
    return {
        onGetScurryDefault:state.onGetScurryDefault,
        onSaveGuestService:state.onSaveGuestService,
    }
}

export default guestServiceScreen = connect(props)(guestServiceScreen);